﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using LuyenThiVer03.UserData;
using Microsoft.Phone.Shell;

namespace LuyenThiVer03
{
    public partial class PageDownloadDeThi
    {
        private CustomBox _cusBox = new CustomBox();
        private int TongSoCau { get; set; }
        private int CauHoiDaLoad { get; set; }
<<<<<<< .mine
        private int MaTranKienThucID { get; set; }
=======
        ListBox curListBox; 
>>>>>>> .r27

        private readonly List<string> _listDeXoa = new List<string>();

        public PageDownloadDeThi()
        {
            InitializeComponent();
            CreateApplicationBar();
        }

        private void pivot_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var index = pivot.SelectedIndex;
            curListBox = GetCurrentListBox(index);
            curListBox.ItemsSource = BindingListDeThi(GetMaMonHoc(curListBox));
            ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IconUri = new Uri(
                        @"\Toolkit.Content\ApplicationBar.Select.png", UriKind.Relative);
            ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).Text = "Chọn";
        }

        private List<MaDeThi> BindingListDeThi(int monHocID)
        {
            var listDeThi = DBHelper.GetListDeThiByMonHoc(monHocID);
            return listDeThi.Select((t, i) => new MaDeThi
                                                  {
                                                      SoThuTu = Convert.ToString(i + 1), NoiDung = Convert.ToString(t.DeThiID), NhomDeThi_ID = t.DeThiID
                                                  }).ToList();
        }

        private void LbDeCoSan_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ListBox)sender).SelectedIndex == -1)
            {
                return;
            }
            var maDe = (MaDeThi) e.AddedItems[0];
            LoadDeThiFromLocalDatabase((int.Parse(maDe.NoiDung)));
            ((ListBox) sender).SelectedIndex = -1;
            e.AddedItems.Clear();
        }

        private void LoadDeThiFromLocalDatabase(int maDe)
        {
            ((App)Application.Current).currentMon = GetTenMonHoc(pivot.SelectedIndex);
            ((App)Application.Current).deso = maDe;
            ((App) Application.Current).DicCauHoi.Clear();
            ((App) Application.Current).DicDapAn.Clear();
            ((App) Application.Current).ListKeyCauHoi.Clear();
            ((App) Application.Current).ListDapAnDung.Clear();
            ((App) Application.Current).ListDapAnUser.Clear();
            ShowThongTinDeThi();
            LoadCauHoiFromLocalDatabase(maDe);
        }

        private void LoadCauHoiFromLocalDatabase(int maDe)
        {
            var listKey = DBHelper.GetListKeyCauHoiByDeThiId(maDe);
            ((App) Application.Current).ListKeyCauHoi = listKey;
            TongSoCau = listKey.Count;
            
            //update UI Cusbox
            _cusBox.tblSoCau.Text = "Số câu : " + TongSoCau;

            foreach (var key in listKey)
            {
                var cauHoi = DBHelper.GetCauHoiByCauHoiId(key);
                MaTranKienThucID = cauHoi.MaTranKienThucID;
                ((App) Application.Current).DicCauHoi.Add(key, cauHoi.NoiDung);
                LoadDapAnFromLocalDatabase(key);
            }
        }

        private void LoadDapAnFromLocalDatabase(long cauHoiId)
        {
            var listDapAn = DBHelper.GetListDapAnByCauHoiId(cauHoiId);
            var listNoiDungDapAn = new List<string>();
            for (var i = 0; i < listDapAn.Count; i++)
            {
                listNoiDungDapAn.Add(listDapAn[i].NoiDung);
                if (listDapAn[i].IsRightAnswer)
                {
                    ((App) Application.Current).ListDapAnDung.Add(i);
                }
            }
            ((App) Application.Current).DicDapAn.Add(cauHoiId, listNoiDungDapAn);
            ((App) Application.Current).ListDapAnUser.Add(new PageLamBaiTracNghiem.DapAnUser(10));
            CauHoiDaLoad++;

            this.Dispatcher.BeginInvoke(() => updateUICustomBox());
        }

        private void updateUICustomBox()
        {
            _cusBox.progressBar.Value += 2;
            _cusBox.tblDangTai.Text = (CauHoiDaLoad * 100) / TongSoCau + " %";
            if (CauHoiDaLoad < TongSoCau) return;
            //SystemTray.GetProgressIndicator(this).IsVisible = false;
            _cusBox.btBatDau.Visibility = Visibility.Visible;
            _cusBox.btBatDau.Click += btBatDau_OnClick;
        }

        private void ShowThongTinDeThi()
        {
            _cusBox = new CustomBox
                          {
                              tblMonThi = {Text = "Môn thi: " + GetTenMonHoc(pivot.SelectedIndex)},
                              tblSoCau = {Text = "Số câu: "},
                              tblThoiGian = {Text = "Thời gian: 60p"}
                          };
            _cusBox.Show();
        }

        private void btBatDau_OnClick(object sender, RoutedEventArgs e)
        {
            _cusBox.Close();
            NavigationService.Navigate(new Uri("/PageLamBaiTracNghiem.xaml?kieuthi=thithu&tongsocau=" + TongSoCau + "&MTKT=" + MaTranKienThucID,
                                               UriKind.Relative));
        }

        private string GetTenMonHoc(int maMonHoc)
        {
            var tenMonHoc = "";
            switch (maMonHoc)
            {
                case 0:
                    tenMonHoc = "Lý";
                    break;
                case 1:
                    tenMonHoc = "Hóa";
                    break;
                case 3:
                    tenMonHoc = "Anh";
                    break;
                case 2:
                    tenMonHoc = "Sinh";
                    break;
            }
            return tenMonHoc;
        }

        private int GetMaMonHoc(ListBox lb)
        {
            switch (lb.Name)
            {
                case "lbDeLyCoSan":
                    return 76;
                case "lbDeHoaCoSan":
                    return 75;
                case "lbDeSinhCoSan":
                    return 74;
                case "lbDeAnhCoSan":
                    return 61;
                default :
                    return 0;
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);
            if (_cusBox.Visibility == Visibility.Visible)
            {
                _cusBox.Close();
            }
        }

        private void CreateApplicationBar()
        {
            ApplicationBar = new ApplicationBar
                                 {
                                     IsVisible = true,
                                     IsMenuEnabled = false
                                 };
            ApplicationBar.Buttons.Add(new ApplicationBarIconButton
                                           {
                                               IconUri =
                                                   new Uri(@"\Toolkit.Content\ApplicationBar.Select.png",
                                                           UriKind.Relative),
                                               IsEnabled = true,
                                               Text = "Chọn"
                                           });
            ((ApplicationBarIconButton) ApplicationBar.Buttons[0]).Click += appBarButton_OnClick;
        }

        private void appBarButton_OnClick(object sender, EventArgs e)
        {
            switch (((ApplicationBarIconButton) sender).Text)
            {
                case "Chọn":
                    ((ApplicationBarIconButton) sender).IconUri = new Uri(
                        @"\Toolkit.Content\ApplicationBar.Delete.png", UriKind.Relative);
                    ((ApplicationBarIconButton) sender).Text = "Xóa";
                    var listBox = GetCurrentListBox(pivot.SelectedIndex);
                    for (var i = 0; i < listBox.Items.Count; i++)
                    {
                        if (listBox.ItemContainerGenerator == null) continue;
                        var item = listBox.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
                        var checkBox = FindFirstElementInVisualTree<CheckBox>(item);
                        checkBox.Visibility = Visibility.Visible;
                    }
                    break;
                case "Xóa":
                    ((ApplicationBarIconButton) sender).IconUri = new Uri(
                        @"\Toolkit.Content\ApplicationBar.Select.png", UriKind.Relative);
                    ((ApplicationBarIconButton) sender).Text = "Chọn";
                    foreach (var xoa in _listDeXoa)
                    {
                        DBHelper.DeleteDeThi(int.Parse(xoa));
                    }
                    
                    var index = pivot.SelectedIndex;
                    curListBox = GetCurrentListBox(index);
                    curListBox.ItemsSource = BindingListDeThi(GetMaMonHoc(curListBox));

                    break;
            }
        }

        private T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
        {
            var count = VisualTreeHelper.GetChildrenCount(parentElement);
            if (count == 0)
                return null;

            for (var i = 0; i < count; i++)
            {
                var child = VisualTreeHelper.GetChild(parentElement, i);

                if (child is T)
                {
                    return (T) child;
                }
                var result = FindFirstElementInVisualTree<T>(child);
                if (result != null)
                    return result;
            }
            return null;
        }

        private void CheckBox_OnChecked(object sender, RoutedEventArgs e)
        {
            var stackpanel = (StackPanel) ((CheckBox) sender).Parent;
            _listDeXoa.Add(((TextBlock) (stackpanel.Children[3])).Text);
        }

        private void CheckBox_OnUnchecked(object sender, RoutedEventArgs e)
        {
            var stackpanel = (StackPanel) ((CheckBox) sender).Parent;
            _listDeXoa.Remove(((TextBlock) (stackpanel.Children[3])).Text);
        }

        private ListBox GetCurrentListBox(int index)
        {
            switch (index)
            {
                case 0:
                    return lbDeLyCoSan;
                case 1:
                    return lbDeHoaCoSan;
                case 2:
                    return lbDeSinhCoSan;
                case 3:
                    return lbDeAnhCoSan;
                default:
                    MessageBox.Show("Lỗi");
                    return null;
            }
        }
    }
}